package com.yami.shop.common.serializer.json;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.util.CacheManagerUtil;
import com.yami.shop.common.util.SpringContextUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Pattern;

@Component
public class ChainJsonSerializer  extends JsonSerializer<String> {

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        CacheManagerUtil cacheManagerUtil = SpringContextUtils.getBean(CacheManagerUtil.class);
        Pattern compile = Pattern.compile("[\\u4e00-\\u9fa5]");
        if(compile.matcher(value).find()){
            gen.writeString(value);
            return;
        }
        if (StrUtil.isBlank(value)) {
            gen.writeString("未知");
            return;
        }

        //cacheManagerUtil.evictCache("SysConfigObject", Constant.SOURCE_CHAIN_CODE);
        Map<String, Map<String,String>> chainMap = cacheManagerUtil.getCache("SysConfigObject", Constant.SOURCE_CHAIN_CODE);
        if (chainMap == null) {
            chainMap = SpringContextUtils.getBean(SqlSession.class).selectMap("com.yami.shop.dao.BlockchainMapper.getChainMap", "code");
            cacheManagerUtil.putCache("SysConfigObject", Constant.SOURCE_CHAIN_CODE, chainMap);
        }
        if(ObjectUtil.isEmpty(chainMap)){
            gen.writeString("未知");
            return;
        }
        // 通过链CODE 回显链上名称
        gen.writeString(ObjectUtil.isEmpty(chainMap.get(value))?"未知":chainMap.get(value).get("name"));
    }
}
